package com.horay.springbootdemo.async.context.controller;

import com.horay.springbootdemo.common.result.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * WebAsyncTask异步控制器
 *
 * @author heyingcheng
 * @date 2019/9/2 0:35
 */
@Slf4j
@RestController
@RequestMapping("async/context")
public class WebAsyncTaskAsyncController {

    @GetMapping("web/async/task")
    public WebAsyncTask<ResultBody<String>> webAsyncTask() {
        Callable<ResultBody<String>> callable = () -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                log.error("WebAsyncTaskAsyncController.webAsyncTask.InterruptedException", e);
            }
            log.info("WebAsyncTaskAsyncController.webAsyncTask方法内部线程：" + Thread.currentThread().getName());
            return new ResultBody("WebAsyncTaskAsyncController.webAsyncTask方法异步的请求响应");
        };
        return getResultBodyWebAsyncTask(callable);
    }

    private <T> WebAsyncTask<T> getResultBodyWebAsyncTask(Callable<T> callable) {
        WebAsyncTask<T> wat = new WebAsyncTask<>(callable);
        wat.onCompletion(() -> log.info("WebAsyncTaskAsyncController.webAsyncTask方法执行完成"));

        wat.onTimeout(() -> {
            log.error("WebAsyncTaskAsyncController.webAsyncTask方法请求超时");
            return (T) ResultBody.RESULT_BODY_FAILURE;
        });

        wat.onError(() -> {
            log.error("WebAsyncTaskAsyncController.webAsyncTask方法请求错误");
            return (T) ResultBody.RESULT_BODY_FAILURE;
        });
        return wat;
    }

}
